package io.github.hadyang.leetcode.offer;

import java.util.LinkedHashMap;
import org.junit.Test;

/** @author haoyang.shi */
public class FirstNotRepeatingChar {

  @Test
  public void test() {
    System.out.println(FirstNotRepeatingChar("abaccde"));
  }

  public int FirstNotRepeatingChar(String str) {
    LinkedHashMap<Character, Integer> data = new LinkedHashMap<>();
    char[] chars = str.toCharArray();
    for (char c : chars) {
      Integer count = data.getOrDefault(c, 0);
      data.put(c, count + 1);
    }

    Character res = null;
    for (Character c : data.keySet()) {
      if (data.get(c) == 1) {
        res = c;
        break;
      }
    }

    if (res == null) {
      return -1;
    }

    for (int i = 0; i < chars.length; i++) {
      if (chars[i] == res) {
        return i;
      }
    }

    return -1;
  }
}
